package com.ciis.system.login.service.impl;

import com.ciis.base.Constants;
import com.ciis.base.Tools;
import com.ciis.base.utils.SessionUtils;
import com.ciis.system.login.service.ILoginService;
import com.ciis.system.relation.domain.TSysRoleAuthority;
import com.ciis.system.relation.service.ISysRoleAuthorityService;
import com.ciis.system.relation.service.ISysUserRoleService;
import com.ciis.system.user.domain.TSysUser;
import com.ciis.system.user.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: zhangdajun
 * Date: 14-5-26
 * Time: 下午10:08
 * To change this template use File | Settings | File Templates.
 */
@Service("loginService")
public class LoginServiceImpl implements ILoginService {

    @Autowired
    ISysUserService userService;

    @Autowired
    ISysUserRoleService userRoleService;

    @Autowired
    ISysRoleAuthorityService roleAuthorityService;

    @Override
    public HashMap<String,String> validateLogin(HttpServletRequest request, String name, String password,String code) throws Exception {
        String sessionCode = (String) SessionUtils.getAttr(request,Constants.SESSION_SECURITY_CODE);
        String loginFailCntStr = (String) SessionUtils.getAttr(request,Constants.SESSION_LOGIN_FAIL_CNT);
        int loginFailCnt = 0;
        if (loginFailCntStr != null) {
            loginFailCnt = Integer.parseInt(loginFailCntStr);
        }
        loginFailCnt ++;
        SessionUtils.setAttr(request,Constants.SESSION_LOGIN_FAIL_CNT, String.valueOf(loginFailCnt));
        HashMap<String,String> mv = new HashMap<String,String>();
        String errInfo = "";
        if (loginFailCnt < 3 || (Tools.notEmpty(sessionCode) && sessionCode.equalsIgnoreCase(code))) {
            TSysUser user = userService.validate(name, password);
            if (user != null) {
                SessionUtils.setUser(request, user);
                // 设置角色信息
                HashMap<String,String> userRoleMap = userRoleService.getRoleMapByUId(user.getId());
                SessionUtils.setRole(request,userRoleMap);
                // 设置权限信息
                HashMap<String,TSysRoleAuthority> roleAuthorityHashMap = roleAuthorityService.getAuthorityMapByUId(user.getId());
                SessionUtils.setRights(request,roleAuthorityHashMap);
                SessionUtils.removeValidateCode(request);
            } else {
                errInfo = "用户名或密码有误！";
            }
        } else {
            errInfo = "验证码输入有误！";
        }
        if (!Tools.isEmpty(errInfo)) {
            mv.put(Constants.RESPONSE_FAILED, errInfo);
            mv.put(Constants.SESSION_LOGIN_FAIL_CNT, String.valueOf(loginFailCnt));
        }
        return mv;
    }
}
